<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启调整"
      inactive-text="关闭调整">
    </el-switch>
    <el-button type="primary" @click="batchSave" v-if="draggable">提交<i class="el-icon-upload el-icon--right"></i>
    </el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" show-checkbox node-key="catId"
             :expand-on-click-node="false" :default-expanded-keys="expandedKey"
             :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop" ref="menuTree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level<=2"
            type="text"
            size="mini"
            @click="() => append(data)">
            Append
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)">
            modify
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name"></el-input>
        </el-form-item>

        <el-form-item label="分类图标">
          <el-input v-model="category.icon"></el-input>
        </el-form-item>

        <el-form-item label="分类单位">
          <el-input v-model="category.productUnit"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitData">确 定</el-button>
  </span>
    </el-dialog>

  </div>

</template>

<script>
// 这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
// 例如：import  《组件名称》  from '《组件路径》 ';

export default {
  // import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data () {
    return {
      data: [],
      draggable: false,
      updateNodes: [],
      dialogType: '',  // add  or modify
      maxDepth: 0,
      title: '',
      category: {
        catId: null,
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: '',
        productUnit: null
      },
      expandedKey: [],
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    handleNodeClick (data) {
      console.log(data)
    },

    // 拖拽的批量保存
    batchSave () {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '更新成功!'
        })
        this.updateNodes = []
        this.maxDepth = 0
      })
    },
    // 批量删除
    batchDelete () {
      let checkedKeys = this.$refs.menuTree.getCheckedKeys()
      console.log('checkedKeys', checkedKeys)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(checkedKeys, false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getMenus()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /*  拖拽时判定目标节点能否被放置。
        type 参数有三种情况：'prev'、'inner' 和 'next'，
        分别表示放置在目标节点前、插入至目标节点和放置在目标节点后 */
    allowDrop (draggingNode, dropNode, type) {
      if (draggingNode.childNodes.length !== 0 && draggingNode.childNodes != null) {
        for (let i = 0; i < draggingNode.childNodes.length; i++) {
          this.maxDepth = draggingNode.childNodes[i].level > this.maxDepth ? draggingNode.childNodes[i].level : this.maxDepth
          this.allowDrop(draggingNode.childNodes[i], dropNode, type)
        }
      } else {
        this.maxDepth = draggingNode.level
      }
      if (type === 'inner') {
        if (this.maxDepth - draggingNode.level + 1 + dropNode.level <= 3) {
          return true
        }
        return false
      } else {
        return this.maxDepth - draggingNode.level + dropNode.level <= 3
      }
    },

    handleDrop (draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', dropNode.label, dropType)

      // 改变挪动对象的 父id，sort排序，层级
      let Pcid = 0
      let siblings = null
      // 1改变挪动对象的 父id
      if (dropType === 'inner') {
        // 如果 inner方式 父子方式改变 父id改变 sort也变 层级改变
        // 父子关系
        Pcid = dropNode.data.catId
        // sort也变=
        siblings = dropNode.childNodes
      } else {
        // 父子关系
        Pcid = dropNode.parent.data.catId === undefined ? 0 : dropNode.parent.data.catId
        // sort也变=
        siblings = dropNode.parent.childNodes
        console.log('after||next', siblings)
      }
      console.log('siblings', siblings)
      // 改变排序 sort  和层级关系
      for (let i = 0; i < siblings.length; i++) {
        // 如果排序到他自己，不仅改变sort 还要改变当前的父id
        // console.log('siblings[i].data.catId----------', siblings[i].data.catId, draggingNode.data.catId)
        // 当前挪动的节点发现它的层级改变了
        if (siblings[i].data.catId === draggingNode.data.catId) {
          if (siblings[i].level !== siblings[i].data.level) {
            this.updateNodes.push({
              catId: siblings[i].data.catId,
              sort: i,
              parentCid: Pcid,
              catLevel: siblings[i].level
            })
            // 必须修改他子节点的层级
            this.upDateChildLevel(siblings[i].childNodes)
          }
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i, parentCid: Pcid})
        } else {
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i})
        }
      }
      console.log('updateNodes', this.updateNodes)
    },

    // 修改所有子节点的层级
    upDateChildLevel (node) {
      console.log('upDateChildLevel开始了', node)
      if (node.length !== null) {
        for (let i = 0; i < node.length; i++) {
          node[i].data.catLevel = node[i].level
          console.log('开始改变子代层级了')
          this.updateNodes.push({catId: node[i].data.catId, catLevel: node[i].level})
          this.upDateChildLevel(node[i])
        }
      }
    },

    // 展示具体对话框
    submitData (data) {
      if (this.dialogType === 'add') {
        // 添加请求
        this.addCategory(data)
      }
      if (this.dialogType === 'modify') {
        // 修改请求
        this.modifyCategory(data)
      }
    },
    // 获取菜单
    getMenus () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        console.log(data.data)
        this.data = data.data
      })
    },
    // 添加方法
    append (data) {
      console.log('append添加函数', data)
      this.dialogType = 'add'
      this.title = '添加'
      this.dialogVisible = true
      this.category.catLevel = data.catLevel * 1 + 1
      this.category.parentCid = data.catId
      this.category.name = ''
      this.category.catId = null
      this.category.icon = null
      this.category.productUnit = null
      console.log('发送前的数据', this.category)
    },
    edit (data) {
      console.log('要修改的数据', data)
      this.dialogType = 'modify'
      this.title = '修改'
      this.dialogVisible = true
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({data}) => {
        console.log('根据id查询的返回结果', data)
        // 回显
        this.category.name = data.data.name
        this.category.icon = data.data.icon
        this.category.catId = data.data.catId
        this.category.productUnit = data.data.productUnit
        this.category.parentCid = data.data.parentCid
      })
    },
    // 添加方法
    addCategory () {
      console.log('提交的三级数据', this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '菜单保存成功!'
        })
        // 关闭对话框
        this.dialogVisible = false
        // 刷新页面保持到当前的节点展开
        this.getMenus()
        this.expandedKey = [this.category.parentCid]
      })
    },
    // 修改方法
    modifyCategory () {
      console.log('修改的三级数据', this.category)
      var {productUnit, icon, name, catId} = this.category
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({productUnit, icon, name, catId}, false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '菜单保存成功!'
        })
        // 关闭对话框
        this.dialogVisible = false
        // 刷新页面保持到当前的节点展开
        this.getMenus()
        this.expandedKey = [this.category.parentCid]
      })
    },
    // 删除方法
    remove (node, data) {
      var ids = [data.catId]
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新
          this.getMenus()
          this.expandedKey = [node.parent.data.catId]
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })

      console.log('node', node)
    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监控 data 中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this 实例）
  created () {
    this.getMenus()
  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () {
  },
  beforeCreate () {
  },
  beforeMount () {
  }, // 生命周期 - 挂载之前
  beforeUpdate () {
  }, // 生命周期 - 更新之前
  updated () {
  }, // 生命周期 - 更新之后
  beforeDestroy () {
  }, // 生命周期 - 销毁之前
  destroyed () {
  }, // 生命周期 - 销毁完成
  activated () {
  } // 如果页面有 keep-alive 缓存功能,这个函数会触发
}
</script>

<style scoped>
</style>
